<template>
  <!-- {{title}} -->
  <div class="main_page {{name}}">
    <back-header title="{{title}}" class="flex_0"></back-header>
    <!-- 工具栏 -->
    <tool-bar defaultOpen selfAdaption>
      <template v-slot:main>
        <tool-bar-item label="" countWidth="250px">
          <!-- 日期范围筛选 -->
          <el-date-picker
            v-model=""
            type="daterange"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            size="mini"
            clearable
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="uploadTimeChange"
            @clear="uploadTimeChange">
          </el-date-picker>
        </tool-bar-item>
        <tool-bar-item label="">
          <el-input v-model="planData." size="mini" placeholder="" clearable></el-input>
        </tool-bar-item>
        <tool-bar-item label="">
          <el-select
            v-model="planData."
            filterable
            remote
            reserve-keyword
            clearable
            placeholder=""
            size="mini"
            :remote-method="searchOperator"
            :loading="searchOperatorLoading">
            <el-option v-for="i in operatorList" :key="i." :label="i." :value="i."></el-option>
          </el-select>
        </tool-bar-item>
        <tool-bar-item label="执行状态">
          <el-select v-model="planData." placeholder="请选择执行状态" size="mini" clearable>
            <el-option :label="item.name" :value="item.id" v-for="item in statusList" :key="item.id"></el-option>
          </el-select>
        </tool-bar-item>
      </template>
      <template v-slot:btn>
        <el-button @click.stop="searchClick()" type="primary" size="mini">搜索</el-button>
        <el-button @click.stop="resetClick()" size="mini">重置</el-button>
        <el-button @click.stop="downloadModel()" size="mini">下载模板</el-button>
        <el-button @click.stop="importStatus=true" size="mini">导入</el-button>
      </template>
    </tool-bar>

    <div class="main_count">
      <ApiTable
        v-loading="tableLoading"
        showOperate
        :tableData="tableData"
        :tableProp="tableProp"
        :showBatch="false"
        operateWidth="200">
        <template v-slot:table-operate="{ content }">
          <el-button type="text" size="small" @click="searchDetail(content)">查看详情</el-button>
          <el-button type="text" size="small" v-if="content.status === 1" @click="deleteItem(content)">删除</el-button>
        </template>
      </ApiTable>
    </div>

    <!-- 导入文件弹窗 -->
    <el-dialog
      title="导入文件"
      :visible.sync="importStatus"
      v-loading="uploadLoading"
      element-loading-text="正在导入"
      width="550px" center top="15%"
      @closed="handleDialogClosed">
      <el-form :model="importInfo" label-width="127px">
        <el-form-item label="选择文件">
          <el-upload
            ref="upload"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            :class="['upload-file', { 'hide': !isShowUploadBox }]"
            :action="。上传文件接口。"
            :before-upload="beforeAvatarUpload"
            :on-remove="handleRemove"
            :on-success="handleFileSuccess"
            :on-error="handlerFileError"
            :on-change="handleFileChange"
            :limit="1"
            :headers="uploadHeaders"
            :auto-upload="false"
            :show-file-list="true"
            size="mini">
            <div class="upload-box"></div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" >
        <el-button size="mini" type="primary" @click="btnUpload">确认上传</el-button>
        <el-button size="mini" @click="importStatus=false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 分页组件 -->
    <pagination :pageNo="pageData.pageNo" :pageSize="pageData.pageSize" :total="totalNum" @paginationChange="paginationChange"></pagination>
  </div>
</template>

<script>
import { ApiTable, ToolBar, ToolBarItem, Pagination, BackHeader } from '@/components'
import {
  batchTableProps, // 批次列表键值组
  batchStatusList // 批次列表执行状态枚举数据
} from './props'
import {
  。批次列表接口。, // 批次列表接口
  。获取操作人列表接口。, // 获取操作人列表接口
  。批次删除接口。, // 批次删除接口
  。上传文件接口。 // 上传文件接口
} from '@/services'
import { getToken } from '@/utils/cookies'
export default {
  components: { ApiTable, ToolBar, ToolBarItem, Pagination, BackHeader },
  data () {
    return {
      tableProp: batchTableProps,
      // 预备搜索参数
      planData: {
        status: null
      },
      // 分页参数
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      // 筛选项
      postData: {
        status: null
      },
      addTime: null,
      optUser: null,
      searchOperatorLoading: false,
      operatorList: [],
      tableLoading: false,
      tableData: [],
      totalNum: 0,
      importStatus: false,
      uploadLoading: false,
      isShowUploadBox: true, // 是否显示上传的入口
      importInfo: {},
      uploadHeaders: { // 上传文件的请求headers
        Authorization: getToken()
      }
    }
  },
  computed: {
    statusList () {
      return [
        {
          id: null,
          name: '全部'
        },
        ...batchStatusList
      ]
    }
  },
  mounted () {
    this.getList()
  },
  methods: {
    /**
     * 获取批次列表
     * @author chaiyf
     * @date {{dateTime}}
     */
    getList () {
      this.tableLoading = true
      let postData = {
        ...this.postData,
        ...this.pageData
      }
      。批次列表接口。(postData).then(({ result, data, msg }) => {
        if (result === 1) {
          let { records = [], total = 0, current, size } = data
          this.tableData = records
          this.tableData.forEach((e, index) => {
            e.sortNum = index + 1 + ((current - 1) * size)
          })
          this.totalNum = total
        } else {
          this.$message.error(msg || data)
        }
      }).finally(() => {
        this.tableLoading = false
      })
    },
    /**
     * 筛选栏导入时间选择赋值
     * @author chaiyf
     * @date {{dateTime}}
     * @param {array} dateArray 日期选择器选择的起始时间到截止时间的数组集合
     */
    uploadTimeChange (dateArray = []) {
      dateArray = dateArray || []
      this.planData = {
        ...this.planData,
        。起始时间参数。: dateArray[0] ? `${dateArray[0]} 00:00:00` : null,
        。截止时间参数。: dateArray[1] ? `${dateArray[1]} 23:59:59` : null
      }
    },
    /**
     * 动态搜索操作人列表
     * @author chaiyf
     * @date 2020-06-18 10:32
     * @param {string} query 模糊搜索输入的文本
     */
    searchOperator (query = '') {
      if (query !== '') {
        this.searchOperatorLoading = true
        。获取操作人接口。({ name: query }).then(({ result, data = [], msg }) => {
          if (result === 1) {
            this.operatorList = data
          } else {
            this.$message.error(msg || data)
          }
        }).finally(() => {
          this.searchOperatorLoading = false
        })
      }
    },
    /**
     * 分页数据变化的时候触发请求
     * @author chaiyf
     * @date {{dateTime}}
     * @param {object} {} 分页数据变化的时候返回的分页数据
     * @param {string|number} pageNo - 分页页数
     * @param {string|number} pageSize - 每页数据量
     */
    paginationChange ({ pageNo, pageSize }) {
      this.pageData.pageNo = pageNo
      this.pageData.pageSize = pageSize
      this.getList()
    },
    /**
     * 筛选栏搜索
     * @author chaiyf
     * @date {{dateTime}}
     */
    searchClick () {
      this.pageData.pageNo = 1
      this.postData = {
        ...this.planData
      }
      this.getList()
    },
    /**
     * 筛选栏重置
     * @author chaiyf
     * @date {{dateTime}}
     */
    resetClick () {
      this.pageData.pageNo = 1
      this.postData = this.planData = {
        。筛选参数充重制。: null
      }
      this.getList()
    },
    downloadModel () {
      window.open('https://qiniu-openfile.imlaidian.com/bm/' + *模版地址*)
    },
    /**
     * 关闭导入批量绑定子商户数据弹窗
     * @author chaiyf
     * @date {{dateTime}}
     */
    handleDialogClosed () {
      this.isShowUploadBox = true
      this.importInfo = {}
      this.$refs.upload.clearFiles()
    },
    /**
     * 点击选择文件上传
     * @author chaiyf
     * @date {{dateTime}}
     */
    btnUpload () {
      const { err, file } = this.importInfo
      if (!file) return this.$message.warning('请先选择文件')
      if (err) return this.$message.error(err)
      this.$refs.upload.submit()
    },
    /**
     * 上传之前校验文件格式
     * @author chaiyf
     * @date {{dateTime}}
     * @returns {boolean}
     */
    beforeAvatarUpload () {
      const { file } = this.importInfo
      this.uploadLoading = true
      return !!file
    },
    /**
     * 文件上传成功回调 - element-ui - upload组件方法
     * @author chaiyf
     * @date {{dateTime}}
     * @param {object} { result, msg } - 结果
     * @param {File} file - 文件
     * @param {array} fileList - 文件列表
     */
    handleFileSuccess ({ result, msg }, file, fileList) {
      if (result === 1) {
        this.$refs.upload.clearFiles()
        this.importStatus = false
        this.resetClick()
        this.$message.success(msg)
      } else {
        this.$message.error(msg)
        this.importInfo.err = msg
      }
      this.uploadLoading = false
      this.isShowUploadBox = false
    },
    /**
     * 文件上传失败回调
     * @author chaiyf
     * @date {{dateTime}}
     */
    handlerFileError () {
      this.uploadLoading = false
      this.isShowUploadBox = true
      this.$message.error('文件上传失败')
    },
    /**
     * 删除上传的文件
     * @author chaiyf
     * @date {{dateTime}}
     * @param {File} file - 文件
     * @param {array} fileList - 文件列表
     */
    handleRemove (file, fileList) {
      this.fileList = fileList
      this.importInfo = {}
      this.isShowUploadBox = true
    },
    /**
     * 文件状态改变
     * @author chaiyf
     * @date {{dateTime}}
     * @param {File} file - 文件
     * @param {array} fileList - 文件列表
     */
    handleFileChange (file, fileList) {
      let reg = /\.xl.{1,2}$/g // 校验上传文件是否为excel
      let isUpload = reg.test(file.name)
      if (!isUpload) {
        this.$refs.upload.clearFiles()
        return this.$message.error('文件格式错误')
      }
      this.isShowUploadBox = false
      this.importInfo = { ...this.importInfo, file }
    },
    /**
     * 查看批次详情
     * @author chaiyf
     * @date {{dateTime}}
     * @param {number} id 批次ID
     */
    searchDetail ({ id }) {
      this.$router.push(。批次详情路由。)
    },
    /**
     * 删除批次
     * @author chaiyf
     * @date {{dateTime}}
     * @param {number} id 批次ID
     */
    deleteItem ({ id }) {
      this.$confirm('确认删除此条批次信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        。删除批次接口。({ batchId: id }).then(({ result, data, msg }) => {
          if (result === 1) {
            this.$message.success('删除成功')
            this.resetClick()
          } else {
            this.$message.error(msg || data)
          }
        })
      })
    }
  }
}
</script>

<style lang="scss">
.batch-approval {
  padding-top: 0;
  .import-button {
    padding: 9px 28px;
  }
  .ml20 {
    margin-left: 20px;
  }
  .mt20 {
    margin-top: 20px;
  }
  .upload-file{
    .el-upload{
      width: 100%;
    }
    .upload-box{
      height: 28px;
      line-height: 28px;
      border: 1px solid #DCDFE6;
      border-radius: 4px;
      display: inline-block;
      width: 100%;
      vertical-align: middle;
    }
  }
  .hide > .el-upload {
    display: none !important;
  }
}
</style>
